package com.zx.controller;

import com.zx.common.commonMethod;
import com.zx.common.ResponseCode;
import com.zx.dto.FoodDTO;
import com.zx.entity.*;
import com.zx.repository.*;
import com.zx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/main")
public class MainController {
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private FoodRepository foodRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private NewsRepository newsRepository;
    @Autowired
    private NoticeRepository noticeRepository;
    @Autowired
    private LinkRepository linkRepository;
    @Autowired
    private CollectRepository collectRepository;
    @Autowired
    private FooddetailRepository fooddetailRepository;
    @Autowired
    private MaterialRepository materialRepository;
    @Autowired
    private CommentRepository commentRepository;

    public void Common(Map<String, Object> map, HttpSession session) {
        commonMethod.common(map, session, userService, categoryRepository,linkRepository,collectRepository);
    }

    //美食分享平台首页
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "page", defaultValue = "0") Integer page,
                              @RequestParam(value = "size", defaultValue = "3") Integer size,
                              Map<String,Object> map,
                              HttpSession session){
        PageRequest request = PageRequest.of(page,size);
        Page<Food> foods = foodRepository.findAll(request);
        List<User> users = userRepository.findAll();
        Page<News> news = newsRepository.findAll(request);
        Page<Notice> notice = noticeRepository.findAll(request);
        Common(map,session);
        map.put("notice",notice);
        map.put("foods",foods);
        map.put("users",users);
        map.put("news",news);
        return new ModelAndView("home/main");
    }
    //美食详情
    @GetMapping("/foodDetail/{foodId}")
    public ModelAndView EditUser(@PathVariable("foodId") Integer id,
                                 Map<String,Object> map,
                                 HttpSession session){
        Common(map,session);
        Food food = foodRepository.getOne(id);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = simpleDateFormat.format(food.getUpdateTime());
        map.put("date",dateStr);
        List<User> users = userRepository.findAll();
        List<Comment> comments = commentRepository.findAllByFoodId(id);
        map.put("comments",comments);
        map.put("users",users);
        map.put("food",food);
        return new ModelAndView("home/foodDetail");
    }
    //美食分类查询
    @GetMapping("/index/{categoryId}")
    public ModelAndView category(@RequestParam(value = "page", defaultValue = "0") Integer page,
                                 @RequestParam(value = "size", defaultValue = "3") Integer size,
                                 @PathVariable("categoryId") Integer categoryId,
                                 Map<String,Object> map,
                                 HttpSession session){
        Common(map,session);
        List<Food> foods = foodRepository.findAllByCategoryId(categoryId);
        PageRequest request = PageRequest.of(page,size);
        Page<News> news = newsRepository.findAll(request);
        Page<Notice> notice = noticeRepository.findAll(request);
        List<User> users = userRepository.findAll();
        map.put("users",users);
        map.put("notice",notice);
        map.put("news",news);
        map.put("foods",foods);
        return new ModelAndView("home/main");
    }
    //系统简介
    @GetMapping("/intro")
    public ModelAndView intro(){
        return new ModelAndView("home/intro");
    }
    //账号设置
    @GetMapping("/setAccount")
    public ModelAndView setAccount(Map<String,Object> map,
                                   HttpSession session){
        List<Category> category = categoryRepository.findAll();
        String username = (String) session.getAttribute("loginUser");
        if(username!=null){
            User user = userService.findUserInfoByUsername(username);
            map.put("category",category);
            map.put("user",user);
            return new ModelAndView("home/setAccount");
        }
        map.put("msg", ResponseCode.NEED_LOGIN.getDesc());
        map.put("url","/foodshare/user/ordinary");
        return new ModelAndView("common/error");
    }
    @PostMapping("/saveUser")
    public ModelAndView saveUser(User user,
                                 Map<String,Object> map){
        userRepository.save(user);
        map.put("url","/foodshare/main/index");
        map.put("msg",ResponseCode.EDIT_SUCCESS.getDesc());
        return new ModelAndView("common/success");
    }
    //图片上传
    @ResponseBody
    @RequestMapping("/upload")
    public Map upload(@RequestParam("file") MultipartFile file){
        String prefix="";
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                //得到原来的文件名
                String originalName = file.getOriginalFilename();
                //获得文件类型(后缀)
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                //获取随机数
                String uuid = UUID.randomUUID().toString();
                //路径
                String filepath = "C:\\Users\\63055\\Pictures\\foodshare\\images\\" +uuid+"." + prefix;
                File files=new File(filepath);
                //文件夹不存在就创建
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                //MultipartFile转换成file类型
                file.transferTo(files);
                Map<String,Object> map2=new HashMap<>();
                Map<String,Object> map=new HashMap<>();
                map.put("code",0);
                map.put("msg","");
                map.put("data",map2);
                map2.put("src","/foodshare/images/"+uuid+"."+prefix);
                return map;
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("code",1);
        map.put("msg","");
        return map;
    }
    //个人中心
    @GetMapping("/personal/{userId}")
    public ModelAndView personal(@RequestParam(value = "page", defaultValue = "0") Integer page,
                                 @RequestParam(value = "size", defaultValue = "4") Integer size,
                                 @PathVariable("userId") Integer userId,
                                 Map<String,Object> map,
                                 HttpSession session){
        Common(map,session);
        User user = userRepository.getOne(userId);
        PageRequest request = PageRequest.of(page,size);
        Page<Food> food = foodRepository.findAllByUserId(userId,request);
        List<Food> count = foodRepository.findAllByUserId(userId);
        map.put("count",count.size());
        map.put("food",food);
        List<Link> link = linkRepository.findAll();
        List<Category> category = categoryRepository.findAll();
        List<Collect> collects = collectRepository.findAllByUserId(userId);
        Integer collectNum = collects.size();
        for (Collect collect:collects
             ) {
            if (collect.getStatus().equals(0))
                collectNum--;
        }
        map.put("collectNum",collectNum);
        map.put("link",link);
        map.put("category",category);
        map.put("ur",user);
        return new ModelAndView("personal/personal");
    }
    //所有美食
    @GetMapping("/food")
    public ModelAndView food(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "2") Integer size,
                             Map<String,Object> map,
                             HttpSession session){
        PageRequest request = PageRequest.of(page,size);
        Page<Food> foods = foodRepository.findAll(request);
        List<User> users = userRepository.findAll();
        Common(map,session);
        map.put("users",users);
        map.put("foods",foods);
        return new ModelAndView("home/food");
    }
    //所有资讯
    @GetMapping("/news")
    public ModelAndView news(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "2") Integer size,
                             Map<String,Object> map,
                             HttpSession session){
        PageRequest request = PageRequest.of(page,size);
        Page<News> news = newsRepository.findAll(request);
        Common(map,session);
        map.put("news",news);
        return new ModelAndView("home/news");
    }
    //搜索功能
    @PostMapping("/search")
    public ModelAndView search(Map<String, Object> map,
                               HttpSession session,
                               @RequestParam("keyword") String keyword){
        Common(map,session);
        if(StringUtils.isEmpty(keyword)){
            keyword = null;
        }
        List<Food> foods = foodRepository.findByKeyword(keyword);
        map.put("foods",foods);
        return new ModelAndView("home/search");
    }
    //收藏功能
    @PostMapping("/collect")
    public ModelAndView collect(Collect collect,
                                Map<String,Object> map,
                                HttpSession session){
        String username = (String) session.getAttribute("loginUser");
        if(StringUtils.isEmpty(username)){
            map.put("msg",ResponseCode.NEED_LOGIN.getDesc());
            map.put("url","/foodshare/main/index");
            return new ModelAndView("common/error");
        }
        Integer foodId = collect.getFoodId();
        Integer userId = collect.getUserId();
        Collect collects = collectRepository.findByUserIdAndFoodId(userId,foodId);
        if(collects == null){
            collectRepository.save(collect);
            return new ModelAndView(new RedirectView("/foodshare/main/index"));
        }else{
            if(collects.getStatus()==0){
                collect.setCollectId(collects.getCollectId());
                collect.setStatus(1);
                collectRepository.save(collect);
                return new ModelAndView(new RedirectView("/foodshare/main/index"));
            }else{
                map.put("msg",ResponseCode.COLLECT_EXISTS.getDesc());
                map.put("url","/foodshare/main/index");
                return new ModelAndView("common/error");
            }
        }
    }
    //主页退出
    @GetMapping("/logout")
    public ModelAndView logout(Map<String,Object> map,
                               HttpSession session){
        session.invalidate();
        map.put("url","/foodshare/main/index");
        map.put("msg",ResponseCode.LOGOUT_SUCCESS.getDesc());
        return new ModelAndView("common/success",map);
    }
    //最新更新
    @GetMapping("/lately")
    public ModelAndView lately(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "3") Integer size,
                               Map<String,Object> map,
                               HttpSession session){
        PageRequest request = PageRequest.of(page,size, Sort.by("updateTime").descending());
        Common(map,session);
        Page<Food> foods = foodRepository.findAll(request);
        Page<Notice> notice = noticeRepository.findAll(request);
        Page<News> news = newsRepository.findAll(request);
        List<User> users = userRepository.findAll();
        map.put("news",news);
        map.put("users",users);
        map.put("notice",notice);
        map.put("foods",foods);
        return new ModelAndView("home/main");
    }
    //收藏最多
    @GetMapping("/mostCollect")
    public ModelAndView mostCollect(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "3") Integer size,
                               Map<String,Object> map){
        List<Food> foods = foodRepository.findAll();
        for (Food food:foods
             ) {
             int count = collectRepository.findAllByFoodId(food.getFoodId()).size();
        }
        map.put("foods",foods);
        return new ModelAndView("home/main");
    }
    //发布功能
    @GetMapping("/publish")
    public ModelAndView publish(HttpSession session,
                                Map<String,Object> map){
        Common(map,session);
        return new ModelAndView("home/publish");
    }
    @PostMapping("/savePublish")
    public ModelAndView savePublish(FoodDTO foodDTO,
                                    Map<String,Object> map,
                                    HttpSession session){
        if(session.getAttribute("loginUser")==null){
            map.put("msg",ResponseCode.NEED_LOGIN.getDesc());
            map.put("url","/foodshare/user/ordinary");
            return new ModelAndView("common/error",map);
        }
        Food food = new Food();
        food.setUserId(foodDTO.getUserId());
        food.setCategoryId(foodDTO.getCategoryId());
        food.setFoodName(foodDTO.getFoodName());
        food.setTitle(foodDTO.getTitle());
        food.setDetail(foodDTO.getDetail());
        food.setImage(foodDTO.getImage());
        foodRepository.save(food);
        List<Fooddetail> fooddetails = foodDTO.getFooddetail();
        for(int i=0;i<fooddetails.size();i++){
            Fooddetail fooddetail = new Fooddetail();
            fooddetail.setFoodId(food.getFoodId());
            fooddetail.setStep(foodDTO.getStep());
            fooddetail.setImage(fooddetails.get(i).getImage());
            fooddetail.setDescribe(fooddetails.get(i).getDescribe());
            fooddetailRepository.save(fooddetail);
        }
        List<Material> materials = foodDTO.getMaterial();
        for(int i=0;i<materials.size();i++){
            Material material = new Material();
            material.setFoodId(food.getFoodId());
            material.setMaterialName(materials.get(i).getMaterialName());
            material.setMaterialUsage(materials.get(i).getMaterialUsage());
            materialRepository.save(material);
        }
        map.put("msg",ResponseCode.SAVE_SUCCESS.getDesc());
        map.put("url","/foodshare/main/index");
        return new ModelAndView("common/success");
    }
}
